package n2_common_methods;

import lombok.extern.slf4j.Slf4j;
import static utils.Sleeper.sleep;
/**
 * join()      等待线程运行结束
 * join(1500) 指定等待最大时间(提前结束将不再等待)
 */
@Slf4j(topic = "c")
public class T5_join {

    static int r = 0;
    public static void main(String[] args) throws InterruptedException {
//        test1();
//        test2();
        test3();
    }

    /**
     * 一个 join
     * @throws InterruptedException
     */
    private static void test1() throws InterruptedException {
        log.debug("main开始");
        Thread t1 = new Thread(() -> {
            log.debug("t1---------开始");
            sleep(1);
            log.debug("t1---------结束");
            r = 10;
        }, "-t1-");
        t1.start();
        /*
        ----------------------------------------
        |                                      /
        |     主线程 阻塞... 等待 t1线程运行结束   /
        |                                      /
        |=======================================
         */
//        t1.join();
/*
join----没使用
16:24:13.895 [main] c. - main开始
16:24:13.941 [-t1-] c. - t1---------开始
16:24:13.941 [main] c. - 结果为:0
16:24:13.944 [-t1-] c. - t1---------结束
join----使用
16:29:11.272 [main] c. - main开始
16:29:11.313 [-t1-] c. - t1---------开始
16:29:11.315 [-t1-] c. - t1---------结束
16:29:11.315 [main] c. - 结果为:10
 */
//        Thread.sleep(2);
        log.debug("结果为:{}", r);
    }


    static int r1;
    static int r2;
    /**
     * 多个 join()
     * @throws InterruptedException
     */
    private static void test2() throws InterruptedException {

        Thread t1 = new Thread(() -> {
            sleep(1);
            r1 = 10;
        });
        Thread t2 = new Thread(() -> {
            sleep(2);
            r2 = 20;
        });
        long start = System.currentTimeMillis();
        t1.start();
        t2.start();
        log.debug("-----join beg-----");
        t1.join();
        log.debug("t1 join end-----");
        t2.join();
        log.debug("t2 join end-----");
        long end = System.currentTimeMillis();
        log.debug("r1: {} r2: {} cost: {}", r1, r2, end - start);
    }

    /**
     * 指定等待最大时间(提前结束将不再等待) join(1500);
     */
    private static void test3() throws InterruptedException {

        Thread t1 = new Thread(() -> {
            sleep(2);
            r1 = 10;
        });

        long start = System.currentTimeMillis();
        t1.start();
        log.debug("-----join beg-----");
        t1.join(1500);
        long end = System.currentTimeMillis();
        log.debug("r1: {} cost: {}", r1,  end - start);
    }


}




